import fs from 'fs'
import archiver from 'archiver'
import OSS from 'ali-oss'
import path from 'path'

const sourceDir = 'E://huyuanbiao//pc//LL002-ZHR-WEB-FRONTEND//build'
const newSourceDir = 'E://huyuanbiao//pc//LL002-ZHR-WEB-FRONTEND//prod'
const targetZip = 'E://huyuanbiao//pc//LL002-ZHR-WEB-FRONTEND//web.zip'
const remoteDir = 'cdn\\prod';

const compressDirectory = () => {
    return new Promise((resolve, reject) => {

        const output = fs.createWriteStream(targetZip);
        const archive = archiver('zip', {
            zlib: { level: 5 } // 最高压缩级别
        });

        output.on('close', () => {
            console.log(`压缩完成，共 ${archive.pointer()} 字节`);
            resolve();
        });

        archive.on('error', (err) => {
            console.log(`压缩失败${err}`);
            reject(err);
        });

        archive.pipe(output);
        archive.directory(sourceDir, false);
        archive.finalize();
    });
}

const uploadDirectoryToOSS = async (localDirPath, ossClient, remoteDirPath) => {
    try {
        const entries = await fs.promises.readdir(localDirPath, { withFileTypes: true });
        for (const entry of entries) {
            const localPath = path.join(localDirPath, entry.name);
            const remotePath = path.join(remoteDirPath, entry.name);

            if (entry.isDirectory()) {
                // 如果是目录，递归上传
                await uploadDirectoryToOSS(localPath, ossClient, remotePath);
            } else {
                // 如果是文件，直接上传
                const content = await fs.promises.readFile(localPath);
                const replacePath = remotePath.replace(/\\/g, '/');
                await ossClient.put(replacePath, content);
            }
        }
        console.log('Directory uploaded to OSS successfully.');
    } catch (error) {
        console.error('Error uploading directory to OSS:', error);
    }
}

const deleteFileOrDirectory = async (filePath) => {
    try {
        // 判断路径是否存在
        if (fs.existsSync(filePath)) {
            // 判断路径是文件还是目录
            const stats = await fs.promises.stat(filePath);
            if (stats.isDirectory()) {
                // 如果是目录，递归删除目录及其内容
                await deleteDirectory(filePath);
            } else if (stats.isFile()) {
                // 如果是文件，直接删除文件
                await fs.promises.unlink(filePath);
            }
        }
    } catch (err) {
        console.error(`删除文件或目录时出错: ${err}`);
        throw err;
    }
}

const deleteDirectory = async (dirPath) => {
    try {
        const files = await fs.promises.readdir(dirPath, { withFileTypes: true });
        for (const file of files) {
            const filePath = path.join(dirPath, file.name);
            if (file.isDirectory()) {
                // 递归删除子目录
                await deleteDirectory(filePath);
            } else {
                // 删除文件
                await fs.promises.unlink(filePath);
            }
        }
        // 删除空目录
        await fs.promises.rmdir(dirPath);
    } catch (err) {
        console.error(`删除目录时出错: ${err}`);
        throw err;
    }
}

export const rename = () => {
    try {
        fs.renameSync(sourceDir, newSourceDir);
        console.log(`Directory renamed from ${sourceDir} to ${newSourceDir}`);
    } catch (error) {
        console.error(`Error renaming directory: ${error}`);
    }
}

export const compress = async () => {
    await compressDirectory()
}

export const upload = async () => {
    const client = new OSS({
        region: 'oss-cn-hangzhou',
        accessKeyId: 'LTAI5tSER5ZvT226iXCBQtwK',
        accessKeySecret: 'k9iiCxaPrSNvcYi2sw95wA7kiHQMVD',
        bucket: 'zhr001',
    });
    await uploadDirectoryToOSS(newSourceDir, client, remoteDir)
}

export const deleteFile = async () => {
    await deleteFileOrDirectory(newSourceDir)
        .then(() => {
            console.log(`${newSourceDir}删除成功！`);
        })
        .catch((err) => {
            console.error(`${newSourceDir}删除失败！`, err);
        });
    await deleteFileOrDirectory(targetZip)
        .then(() => {
            console.log(`${targetZip}删除成功！`);
        })
        .catch((err) => {
            console.error(`${targetZip}删除失败！`, err);
        });
}
